package com.example.mybatispermission.controller;

import com.example.mybatispermission.entry.Permission;
import com.example.mybatispermission.entry.Role;
import com.example.mybatispermission.mapper.PermissionMapper;
import com.example.mybatispermission.mapper.RoleMapper;
import lombok.AllArgsConstructor;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("role")
@AllArgsConstructor
public class RoleController {
    private RoleMapper roleMapper;
    private PermissionMapper permissionMapper;
    @GetMapping("list")
    @RequiresPermissions("role:select")
    public String getRoleList(Model model){
        model.addAttribute("roles", roleMapper.selectList(null));
        return "role_list";
    }
    @GetMapping("info")
    @RequiresPermissions("role:select")
    public String getRoleInfo(@RequestParam(required = false) Integer id, Model model){
        if (id == null) {
            model.addAttribute("role", new Role());
            model.addAttribute("title", "新增角色");
            model.addAttribute("hasPermissions", new ArrayList<Permission>());
        } else {
            Role role = roleMapper.selectById(id);
            model.addAttribute("role", role);
            model.addAttribute("title", "修改角色");
            model.addAttribute("hasPermissions", permissionMapper.getPermissionsByRole(role));
        }
        model.addAttribute("permissions", permissionMapper.selectList(null));
        return "role_info";
    }
    @PostMapping("addOrModify")
    @RequiresPermissions(value = {"role:insert", "role:update"}, logical = Logical.OR)
    public String modifyRole(Role role, @RequestParam List<Integer> permissions){
        if (role.getId() == null) {
            roleMapper.insert(role);
        } else {
            roleMapper.updateById(role);
            roleMapper.clearPermissions(role);
        }
        roleMapper.bindPermission(role, permissionMapper.selectBatchIds(permissions));
        return "redirect:/role/list";
    }
    @GetMapping("delete")
    @RequiresPermissions("role:delete")
    public String deleteRole(Integer id){
        roleMapper.deleteById(id);
        return "redirect:/role/list";
    }

}
